//
//  DeviceList.m
//  efairy
//  展示某一项目的设备列表
//  Created by 李锋 on 2019/1/11.
//  Copyright © 2019年 East. All rights reserved.
//

#import "DeviceList.h"
#import "DeviceListCell.h"
#import "EFAModel.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "DeviceListModel.h"
#import "OYRPopOption.h"
#import "EFADeviceMapVC.h"
#import "EFADeviceInfoVC.h"
#import "DeviceDetailInfo.h"

@interface DeviceList ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITextField *searchView;
@property(nonatomic,strong)  UIButton *leftButton;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray<DeviceListItem *> *deviceArray;

@property(nonatomic,assign) int pageIndex;
@property (nonatomic, strong) MJRefreshComponent *refreshViewComponent;

@property(nonatomic,assign) int alarmType;

@end

@implementation DeviceList

- (void)viewDidLoad {
    [super viewDidLoad];
    _alarmType = -1;
    [self initNavigationBar];
    [self setupView];
    
}

//隐藏底部导航栏
- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}


- (void)initNavigationBar {
    
     self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
   
    
    //开始创建左边按钮
    _leftButton =  [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    [_leftButton setTitle:@"全部" forState:UIControlStateNormal];
    _leftButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [_leftButton setTitleColor:ColorFromRGB(0x333333) forState:UIControlStateNormal];
    [_leftButton setImage:[UIImage imageNamed:@"icon_arrow_bottom"] forState:UIControlStateNormal];
    //button文字在左边图片在右 （button默认是图片左文字右）
    [_leftButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -_leftButton.imageView.size.width, 0, _leftButton.imageView.size.width)];
    [_leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, _leftButton.titleLabel.bounds.size.width, 0,-_leftButton.titleLabel.bounds.size.width)];
    [_leftButton addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
//    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:_leftButton];
    UIBarButtonItem *lfetButtonitem=[[UIBarButtonItem alloc] initWithCustomView:_leftButton];
    
    //右侧图标
    
     UIBarButtonItem *rightButtonItem= [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_device_location"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    self.navigationItem.rightBarButtonItems = @[lfetButtonitem,rightButtonItem];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_device_location"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    
    
    //创建左侧搜索图标
    UIImageView *searchIcon=[[UIImageView alloc]init];
    searchIcon.image=[UIImage imageNamed:@"search_icon"];
    
    //文本输入框
    _searchView = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 240, 30)];
    _searchView.backgroundColor = ColorFromRGB(0xefefef);
    _searchView.clearButtonMode=UITextFieldViewModeAlways;//只要输入框有内容就出现
    _searchView.placeholder = @"请输入设备昵称或UUID";    // 设置提示文字
    _searchView.layer.borderWidth=0.0f;
    _searchView.font = [UIFont systemFontOfSize:12.0];
    _searchView.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    _searchView.delegate = self;//设置代理
    
    _searchView.leftViewMode = UITextFieldViewModeAlways;
    self.navigationItem.titleView = [[UIView alloc]init];
    self.navigationItem.titleView.backgroundColor = ColorFromRGB(0xefefef);
    self.navigationItem.titleView.height = 30;
    self.navigationItem.titleView.width = 205;
    self.navigationItem.titleView.layer.cornerRadius = 16.0f;
    [self.navigationItem.titleView sd_addSubviews:@[searchIcon,_searchView]];
    //    [self.navigationItem.titleView sd_addSubviews:@[searchIcon,_mapView,_searchView]];
    searchIcon.sd_layout.widthIs(15)
    .heightIs(15)
    .topSpaceToView(self.navigationItem.titleView, 7.5)
    .leftSpaceToView(self.navigationItem.titleView, 10);
    _searchView.sd_layout.leftSpaceToView(searchIcon, 10)
    .rightSpaceToView(self.navigationItem.titleView, 10);
}


//主体viwe用于显示tableview的cell
-(void) setupView{
   
    float  navigationbar = self.navigationController.navigationBar.frame.size.height;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, statusBarHeight+navigationbar, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-navigationbar)];
    self.tableView.backgroundColor = BG;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //多余分割线不显示
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view sd_addSubviews:@[ self.tableView ]];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weakSelf = self;
    //..下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
        weakSelf.pageIndex = 1;
        [weakSelf requestDeviceListWithHeader:YES];
    }];

    //..上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
        weakSelf.pageIndex = weakSelf.pageIndex + 1;
        [weakSelf requestDeviceListWithHeader:NO];
    }];
    
    
   
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
}

//搜索 这个函数是重写UITextFieldDelegate 当点击键盘搜索按钮触发
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    _pageIndex = 1;
    [self requestDeviceListWithHeader:YES];
    return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_deviceArray!=nil && _deviceArray.count > 0){
        return _deviceArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DeviceListCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"DeviceListCell" description]];
    if(!cell){
        cell = [[DeviceListCell alloc]init];
    }
    
    [cell setModelData:_deviceArray[indexPath.row]];
     // 此步设置用于实现cell的frame缓存，可以让tableview滑动更加流畅
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
    //    return [tableView cellHeightForIndexPath: indexPath];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor whiteColor];
}

//接受点击cell item项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.deviceArray.count) {
        [self jumpToDeviceInfoWithDeviceListItem:self.deviceArray[indexPath.row]];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - private methods
- (void)jumpToDeviceInfoWithDeviceListItem:(DeviceListItem *)item {
//    EFADeviceInfoVC *vc = [[EFADeviceInfoVC alloc] init];
    DeviceDetailInfo *vc = [[DeviceDetailInfo alloc] init];
    vc.deviceId = item.efairydevice_id;
    vc.device_name = item.efairydevice_name;
    [self showViewController:vc sender:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}


//刷新数据
- (void)refreshWholeView {
    [self.tableView reloadData];
}


-(void)leftBtnClick:(UIButton *)optionButton{
    // 注意：由convertRect: toView 获取到屏幕上该控件的绝对位置。
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    CGRect frame = [optionButton convertRect:optionButton.bounds toView:window];
    //自定义Uiview 类似于android popupview
    OYRPopOption *s = [[OYRPopOption alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    s.option_optionContents = @[@"全部", @"正常", @"火警",@"预警",@"故障",@"离线"];
        //设置图标
    //s.option_optionImages = @[@"icon_quit_matchdetail",@"icon_nav_share",@"icon_invite_matchdetail"];
    // 使用链式语法直接展示 无需再写 [s option_show];
    [[s option_setupPopOption:^(NSInteger index, NSString *content) {
        switch (index) {
            case 0:
                [_leftButton setTitle:@"全部" forState:UIControlStateNormal];
                _alarmType = -1;
                
                break;
            case 1:
                [_leftButton setTitle:@"正常" forState:UIControlStateNormal];
                _alarmType = 6;
                
                break;
            case 2:
                [_leftButton setTitle:@"火警" forState:UIControlStateNormal];
                _alarmType = 1;
                
                break;
            case 3:
                [_leftButton setTitle:@"预警" forState:UIControlStateNormal];
                _alarmType = 2;
                
                break;
            case 4:
                [_leftButton setTitle:@"故障" forState:UIControlStateNormal];
                 _alarmType = 3;
                break;
            case 5:
                [_leftButton setTitle:@"离线" forState:UIControlStateNormal];
                _alarmType = 0;
                break;
            default:
                break;
        }
        _pageIndex = 1;
        [self requestDeviceListWithHeader:YES];
    } whichFrame:frame animate:YES] option_show];
}



-(void)rightBtnClick{
    NSLog(@"地图按钮被点击了哦");
    EFADeviceMapVC *vc = [[EFADeviceMapVC alloc] init];
    vc.device_list = self.deviceArray;
    [self showViewController:vc sender:nil];
}

#pragma mark - network request
- (void)requestDeviceListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        //        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    //    NSInteger startIndex = isHeader ? 0 : self.deviceModel.device_list.count;
    //    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
    //                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token
    ////                           @"efairyproject_id" : @(1)
    //                           };
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    if(_alarmType > -1){
        [pars setObject:@(_alarmType) forKey:@"efairydevice_alarm_id"];
    }
    [pars setObject:@(self.project_id) forKey:@"efairyproject_id"];

    if (_searchView.text.length >0){
        [pars setObject:_searchView.text forKey:@"keyword"];
    }
    [pars setObject:@(_pageIndex) forKey:@"page"];
    [pars setObject:@"20" forKey:@"pageSize"];
   
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表：%@", responseObject);
         [hud hideAnimated:NO];
        [self tableViewEndRefresh:isHeader];
        //把服务端返回的json格式数据解析为对象
        DeviceListModel *deviceModel = [DeviceListModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        //服务端返回本次请求的项目列表数据
        if(deviceModel.device_list != nil){
            if(isHeader){
                //下拉刷新
                _deviceArray = deviceModel.device_list;
            }else{
                //上啦加载追加数据到数组
                [_deviceArray addObjectsFromArray:deviceModel.device_list];
            }
            if(_deviceArray.count >= deviceModel.total_rows){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }
        }
        [self refreshWholeView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}



@end
